package com.example.auth.config;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.example.auth.enums.RoleEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xijie.wang
 * @decription:权限校验
 * @date 2022-04-11 15:43
 */
@Configuration
@Slf4j
public class WebConfigurer implements WebMvcConfigurer {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		//开启路由鉴权
		registry.addInterceptor(new SaRouteInterceptor((request, response, handler) -> {
			log.info(">>> 请求完整路径:{}", request.getUrl());
			//登录拦截 鉴权
			SaRouter.match("/**")
					.notMatch(notLogin())
					.check(StpUtil::checkLogin);

			// 产品权限、订单管理、财务管理、资料管理、数据中心 权限
			SaRouter.match(authPermission())
					.notMatch(notAuth())
					.check(() -> StpUtil.checkRole(RoleEnum.AUTH.getCode()));
		}));
	}

	public static List<String> notLogin() {

		List<String> allows = new ArrayList<>();
		allows.add("//user/**");
		allows.add("/ll/channel/front/channel/register");
		allows.add("/ll/channel/front/verifyCode/get");

		//swagger资源放行
		allows.add("/v2/**");
		allows.add("/v3/**");
		allows.add("/swagger-ui.html/**");
		allows.add("/swagger-ui/**");
		allows.add("/doc.html/**");
		allows.add("/api-docs-ext/**");
		allows.add("/swagger-resources/**");
		allows.add("/webjars/**");
		allows.add("/favicon.ico");
		allows.add("/error");

		return allows;
	}

	/**
	 * 订单管理、财务管理、资料管理、数据中心 权限
	 *
	 * @return
	 */
	public static List<String> authPermission() {

		List<String> allows = new ArrayList<>();
		//产品权限
		allows.add("/ll/channel/product/**");

		return allows;
	}

	/**
	 * 不鉴权 但是需要登录认证
	 * @return
	 */
	public static List<String> notAuth() {
		List<String> allows = new ArrayList<>();
		allows.add("/ll/channel/product/list/que");
		return allows;
	}
}
